package com.magold.logic.region.airflow;

import java.util.Random;

import org.andengine.entity.particle.Particle;
import org.andengine.entity.particle.initializer.IParticleInitializer;
import org.andengine.entity.shape.IAreaShape;

import com.badlogic.gdx.physics.box2d.Body;
import com.magold.logic.LogicComponentFinder;
import com.magold.physics.MagoldPhysicsConnector;
import com.magold.sprite.IMultiTextureSprite;

public class ApplyPhysicsInitializer implements IParticleInitializer<IMultiTextureSprite>{
	private static final Random random = new Random();
	
	private IAreaShape mRangeShape;
	private float mVelocityValue;
	
	
	public ApplyPhysicsInitializer(float pWindSpeed, IAreaShape pRangeShape) {
		mVelocityValue = pWindSpeed;
		mRangeShape = pRangeShape;
	}

	@Override
	public void onInitializeParticle(Particle<IMultiTextureSprite> pParticle) {
		IMultiTextureSprite shape = pParticle.getEntity();
		MagoldPhysicsConnector mConnector = LogicComponentFinder.findConnector(shape);
		mConnector.setPhysicsEnabled(true);
		mConnector.updateBodyToShape();
		
		Body body = mConnector.getBody();
		float[] original = mRangeShape.convertLocalToSceneCoordinates(0, 0);
		float x1 = original[0], y1 = original[1];
		
		float currentVelocity = mVelocityValue * (1.0f - (random.nextFloat()*0.1f-0.05f));
		float[] velocity = mRangeShape.convertLocalToSceneCoordinates(0, -currentVelocity);
		float vx= velocity[0] - x1;
		float vy= velocity[1] - y1;
		
		body.setLinearVelocity(vx, vy);
	}

}
